<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      :before-open="beforeOpen"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      :page.sync="page"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #cover="scope">
        <img :src="scope.row.cover + '?x-oss-process=image/resize,m_fill,h_50,w_50'" alt="">
      </template>
      <template slot="menuLeft">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click.stop="handleAdd()"
        >
          新增任务
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="source">
        <div style="text-align:center">
          <i :class="row.source"/>
        </div>
      </template>
      <template slot-scope="{row}" slot="time">
        <div>开始时间：{{row.time[0]}}</div>
        <div>结束时间：{{row.time[1]}}</div>
      </template>
      <template slot-scope="{row}" slot="status">
        <el-tag v-show="row.status!=2 && row.status!=4" type="info">
          {{ transteStatus(row.status)}}
        </el-tag>
        <el-tag v-show="row.status==4" type="warning">
          {{ transteStatus(row.status)}}
        </el-tag>
        <el-tag v-show="row.status==2" type="success">
          {{ transteStatus(row.status)}}
        </el-tag>
      </template>      
      <template slot-scope="{row}" slot="menu">
        <el-button
          type="text"
          icon="el-icon-delete"
          size="small"
          @click="rowDel(row)"
           v-if="row.status != 2"
        >
         删除
        </el-button>
        <el-button
          type="text"
          icon="el-icon-circle-plus-outline"
          size="small"
          @click="gotoEdit(row)"
          v-if="row.status != 2"
        >
         编辑
        </el-button>
        <el-button
          v-if="row.status == 1"
          type="text"
          icon="el-icon-upload2"
          size="small"
          @click="gotoPublish(row)"
        >
         发布
        </el-button>
         <el-button
          v-if="row.status == 2"
          type="text"
          icon="el-icon-download"
          size="small"
          @click="gotoXiajia(row)"
        >
         下架
        </el-button>
      </template>
    </avue-crud>
    <div v-show="openTaskFlag">
       <el-dialog
        :title="dialogTitle"
        :visible.sync="openTaskFlag"
        width="50%"
        top="30px"
        :modal-append-to-body="false"
        :before-close="handleClose"
      >
        <avue-form ref="addRef" :option="option" v-model='addForm' @submit="handleSubmit">
          <template slot-scope="{}" slot="resource">
            <div class="img-box">
              <template v-for="(item,idx) in addForm.resource">
                  <span v-if="item.type==4" @click="delResouse(item)">
                    <span>素材组-{{item.name}}  </span><span style="color: red;" v-if="useRsource">有效素材【{{useRsource}}】个</span>
                  </span>
              </template>
              <el-button @click="openResource()" style="margin-left: 20px;">选择素材</el-button>
            </div>
          </template>
          <template slot-scope="{}" slot="cover">
            <div class="img-box">
              <template v-if="addForm.cover">
                  <span @click="delResouse()">
                    <img  :src="addForm.cover + '?x-oss-process=image/resize,m_fill,h_50,w_50'" alt="">
                  </span>
              </template>
              <el-upload
                 ref="upload"
                 class="upload-demo"
                 btn
                 action="123"
                 :before-upload="beforeImport"
                 :http-request="uploadSectionFile"
                 accept='.png,.jpg'
                 :limit='1'
               >
                 <el-button>选择封面</el-button>
               </el-upload>

            </div>
          </template>
        </avue-form>
      </el-dialog>
    </div>
    <div v-if="openSourceFlag">
      <Dialog v-model="openSourceFlag" :selectArr="addForm.resource" @selChange="selChange" />
    </div>
    <div v-if="resourceFlag">
       <el-dialog
        title="查看资源"
        :visible.sync="resourceFlag"
        width="550px"
        top="30px"
        :append-to-body='true'
        >
        <div v-for="(item,idx) in resourceArr" :key="idx">
          <img width="500px" v-if="item.type==2" :src="item.url" alt="">
          <video width="500px" height="500px" v-if="item.type==3" :src="item.url"  controls="controls" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="resourceFlag = false">关 闭</el-button>
        </span>
      </el-dialog>
    </div>

  </basic-container>
</template>

<script>
  import dayjs from 'dayjs'
  import Dialog from '@/views/resource/dialog.vue'
  import {signFile} from '@/api/common'
  import {submit,getList,remove,publish,xiajia,getResourceNumber} from "@/api/task/mytask";
  import {mapGetters} from "vuex";
  export default {
    components:{Dialog},
    data() {
      return {
        form: {},
        addForm:{},
        box: false,
        useRsource:'',
        openTaskFlag:false,
        openSourceFlag:false,
        submitLoading:false,
        resourceFlag:false,
        resourceArr:[],
        dialogTitle:'新增任务',
        props: {
          label: "title",
          value: "key"
        },
        menuGrantList: [],
        dataScopeGrantList: [],
        apiScopeGrantList: [],
        apiGrantList: [],
        menuTreeObj: [],
        dataScopeTreeObj: [],
        apiScopeTreeObj: [],
        selectionList: [],
        query: {},
        loading: true,
        currolid:null,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          selection: true,
          viewBtn: false,
          editBtn:false,
          addBtn:false,
          delBtn:false,
          dialogWidth: 900,
          dialogClickModal: false,
          labelWidth:110,
          columnBtn:false,
          height: 'auto',
          calcHeight: 40,
          menuPosition: 'right',
          column: [
            {
              label: "任务封面",
              prop: "cover",
              search:true,
              span: 24,
              rules: [
                {
                  required: true,
                  message: "请上传封面",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "任务名称",
              prop: "name",
              search:true,
              span: 24,
              showOverflowTooltip:true,
              rules: [
                {
                  required: true,
                  message: "请输入任务名称",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "所属城市",
              prop: "city",
              type:'select',
              dicUrl: "/api/oms-system/base/citylist?current=1&size=1000",
              span: 12,
              search:true,
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择所属城市",
                trigger: "click"
              }]
            },
             {
              label: "所属平台",
              prop: "platForm",
              dicUrl: "/api/oms-system/base/platformlist?current=1&size=1000",
              span: 12,
              type:'select',
              search:true,
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择所属平台",
                trigger: "click"
              }]
            },
            {
              label: "所属行业",
              prop: "category",
              dicUrl: "/api/oms-system/base/categorylist?current=1&size=1000",
              type:'select',
              span: 12,
              showOverflowTooltip:true,
              props: {
                label: "name",
                value: "id"
              },
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
              rules: [{
                required: true,
                message: "请选择所属行业",
                trigger: "click"
              }]
            },
            {
              label: "所属广告商",
              prop: "advertise",
              dicUrl: "/api/oms-system/base/myadvertiserlist?current=1&size=1000",
              span: 12,
              showOverflowTooltip:true,
              props: {
                label: "name",
                value: "id"
              },
              type:'select',
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
              rules: [{
                required: true,
                message: "请选择所属广告商",
                trigger: "click"
              }]
            },
            {
              label: "任务等级",
              prop: "taskgrade",
              dicUrl: "/api/oms-system/base/taskgradelist?current=1&size=1000",
              span: 12,
              props: {
                label: "name",
                value: "id"
              },
              type:'select',
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
              rules: [{
                required: true,
                message: "请选择任务等级",
                trigger: "click"
              }]
            },

            {
              label: "时间范围",
              prop: "time",
              align:'center',
              span: 12,
              width:200,
              type:'datetimerange',
              slot:true,
              rules: [
                {
                  required: true,
                  message: "请输入时间范围",
                  trigger: "blur"
                }
              ]
            },
            {
              align:'center',
              type:'number',
              label: "任务状态",
              prop: "status",
              span: 24,
              slot:true,
              display:false,
            },
            {
              type:'number',
              label: "奖励金额(元)",
              prop: "price",
              precision:2,
              min:0.30,
              max:10.00,
              step:0.01,
              align:'center',
              span: 12,
              rules: [
                {
                  required: true,
                  message: "请输入任务金额",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "选择素材",
              prop: "resource",
              span: 24,
              formslot:true,
              hide:true,
              rules: [
                {
                  required: true,
                  message: "请上传素材",
                  trigger: "blur"
                }
              ]
            },
            {
              type:'textarea',
              label: "任务要求",
              prop: "remark",
              showOverflowTooltip:true,
              span:24,
              hide:false
            },
            {
              label: "更新时间",
              prop: "updatedTime",
              width:150,
              align:'center',
              display:false
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["userInfo"]),
    },
    methods: {
      transteStatus(type){
        if(type == 1){
          return '待发布'
        }else if(type == 2){
          return '已发布'
        }else if(type == 3){
          return '已撤销'
        }else if(type == 4){
          return '已过期'
        }else if(type == 5){
          return '已完成'
        }else if(type == 6){
          return '未开始'
        }
      },
      goToResource(row){
         const urls = row.resourceUrls.split(',')
         const types = row.resourceTypes.split(',')
         this.resourceArr = urls.map((item,idx)=>{
           return {url:item,type:types[idx]}
         })
         this.resourceFlag = true
      },
      async gotoPublish(row){
        this.$confirm("确定要发布吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return publish({id:row.id});
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "发布成功!"
            });
          });
      },
      gotoXiajia(row){
        this.$confirm("确定要下架吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return xiajia({id:row.id});
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "下架成功!"
            });
          });
      },
      gotoEdit(row){
        this.dialogTitle = '编辑任务'
        const copyRow = JSON.parse(JSON.stringify(row))
        const urls = copyRow.resourceUrls.split(',')
        const types = copyRow.resourceTypes.split(',')
        const resourceIds = copyRow.resource.split(',')
        const newArr = resourceIds.map((item,idx)=>{
         return {id:item,url:urls[idx],type:types[idx]}
        })
        copyRow.resource = newArr
        this.addForm = copyRow
        const data = this.option.column.find(item=>item.prop=='num')
        this.openTaskFlag = true;
      },
      async handleSubmit(data,done){
        const obj = {
          name: data.name,
          cover: data.cover,
          advertise:  data.advertise,
          category:  data.category,
          city:  data.city,
          platForm: data.platForm,
          price:  data.price,
          resource:  data.resource||[],
          taskgrade:  data.taskgrade,
          time: [dayjs(data.time[0]).format('YYYY-MM-DD HH:mm:ss'),dayjs(data.time[1]).format('YYYY-MM-DD HH:mm:ss')],
          remark:  data.remark
        }
        if(obj.resource.length==0){
          this.$message({
            type: "error",
            message: "请选择素材组!"
          });
        }
        if(data.id){
          obj['id'] = data.id;
         const resData = await submit(obj)
          done()
          if(resData.data.code ==200){
              this.openTaskFlag = false;
              this.onLoad(this.page, this.query);
          }
          this.submitLoading = false
        }else{
          const resData = await submit(obj)
          console.log('~~~~~~~~resData~~~~~~~',resData)
          if(resData.data.code ==200){
              this.openTaskFlag = false;
              this.onLoad(this.page, this.query);
              done()
          }
          this.submitLoading = false
        }
         done()

      },
      handleAdd(){
        this.dialogTitle = '新增任务'
        const data = this.option.column.find(item=>item.prop=='num')
         console.log('~~~~~~~~~~handleAdd~~~~~~~~~~~',data)
         // data.disabled = false
        this.openTaskFlag = true;
      },
     async selChange(data){
       this.useRsource=0
        this.addForm.resource = JSON.parse(JSON.stringify(data))
        this.openSourceFlag = false;
        this.openTaskFlag = true;
        const idList = data.map(item => item.id)
        const res = await getResourceNumber(idList[0])
        if(res.data.data){
            this.useRsource = res.data.data
        }
      },
      delResouse(item){
        const newResource = this.addForm.resource
        newResource.forEach((child,idx)=>{
          if(child.url == item.url){
            newResource.splice(idx,1)
          }
        })
        this.addForm.resource = newResource
      },
      handleClose(){
         this.addForm.id = '';
         this.addForm.cover = '';
         this.$refs.addRef.resetForm();
         this.openTaskFlag = false;
      },
      openResource(){
        this.$nextTick(()=>{
           this.openSourceFlag = true;
           this.openTaskFlag = false;
        })
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove({id:row.id});
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      beforeOpen(done, type) {
        done();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList({current:page.currentPage, size:page.pageSize,taskType:3, ...params}).then(res => {
          const resData = res.data.data.list;
          this.page.total = res.data.data.total;
          resData.forEach(item=>{
            item.time = [item.startTime,item.endTime]
          })
          this.data = resData;
          this.loading = false;
        });
      },
      beforeImport(file){
        if (!file || !file.name || !file.type || !file.size) {
          this.$message({
            type: 'warning',
            message: '不支持上传空文件!',
          })
          return false
        }
        if (!file.name.endsWith('.png') && !file.name.endsWith('.jpg')) {
          this.$message({
            type: 'warning',
            message: '不支持上传当前文件类型!',
          })
          return false
        }
        return true
      },
      async uploadSectionFile(data)  {
        this.configLoading = true;
        const file = data.file;
        const ossurl = 'https://s.xazyzx.com/'
        const res = await signFile({name:file.name})
        const signData = res.data.data
         // ⽂件对象
        const formData = new FormData()
        if(res.data.code == 200){
            formData.append("signature", signData.signature);
            formData.append("name", signData.filename);
            formData.append("policy", signData.policy);
            formData.append("OSSAccessKeyId", signData.ossAccessKeyId);
            formData.append("success_action_status", "200");
            formData.append("key", signData.dir +'/'+ signData.filename);
            formData.append('file', file)
            fetch(signData.host, {
              method: "POST",
              body: formData,
            }).then((response) => {
              this.configLoading = false;
              if (!response.ok) {
                throw new Error("文件上传到OSS失败");
              }else{
                  this.$set(this.addForm,'cover',ossurl + signData.dir +'/'+ signData.filename)
              }
            });
        }else{
          this.$refs.upload.clearFiles()
          this.$message({
            type: 'warning',
            message: '服务端签名失败',
          })
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
.img-box{
  display: flex;
  img{
    margin-right: 10px;
  }
  div{
    text-align: center;
    line-height: 20px;
  }
}
</style>
